package com.why.catchMsg.common;

import com.why.catchMsg.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        String url=httpServletRequest.getRequestURI();
        ModelAndView mv=null;
        String defalutMsg="系统错误";
        // .json , .page
        if(url.endsWith(".json")){
             if(e instanceof BizException){
                JsonData result=JsonData.fail(((BizException) e).getErrorMessage());
                mv=new ModelAndView("jsonView",result.toMap());
                log.error("操作异常");
            }else{
                log.error("不知道的异常:"+url,e);
                JsonData result=JsonData.fail(defalutMsg);
                mv=new ModelAndView("jsonView",result.toMap());
            }
        }else if(url.endsWith(".page")){
            log.error("异常页面:"+url,e);
            JsonData result=JsonData.fail(defalutMsg);
            mv=new ModelAndView("exception",result.toMap());
        }else{

            log.error("不知道的异常:"+url,e);
            JsonData result=JsonData.fail(defalutMsg);
            mv=new ModelAndView("jsonView",result.toMap());

        }
        return mv;
    }
}
